from django import http



# Create your views here.
from django.core.cache import cache
from django.views import View

from areas.models import Area

from meiduo_mall.utils.response_code import RETCODE
import logging
logger = logging.getLogger('django')

class AreasView(View):

    """省市区数据"""
    def get(self,request):
        """获取省市区数据逻辑处理"""
        # 如果前端没有传入area_id，表示用户需要省份数据
        # 如果前端传入了area_id，表示用户需要市或区数据
        area_id = request.GET.get('area_id')
        if not area_id:
            # 获取判断是否有缓存
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    # 查询省份数据
                    province_model_list = Area.objects.filter(parent__isnull=True)
                    # 遍历省份数据把模型类结果集转换成Python列表
                    province_list =[]
                    for province_model in province_model_list:
                        province_list.append(
                            {
                                'id': province_model.id,
                                'name': province_model.name
                            }
                        )
                        # 缓存省份字典列表数据:默认存储到别名为"default"的配置中
                        cache.set('province_list',province_list,3600)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'省份数据获取失败'})

            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','province_list':province_list})
        else:
        
            # 判断是否有缓存
            sub_data = cache.get('sub_area_' + area_id)
            if not sub_data:
                try:
                    # 获取城市或市区县数据
                    parent_model =Area.objects.get(id=area_id)
                    sub_model_list= parent_model.subs.all()

                    # 将子级模型列表转换成字典列表
                    subs = []
                    for sub_model in sub_model_list:
                        subs.append({
                              "id":sub_model.id,
                              "name":sub_model.name
                            })
                    # 构造子级JSON数据
                    sub_data = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': subs
                    }
                    # 缓存城市或者区县
                    cache.set('sub_area_' + area_id, sub_data, 3600)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '查询城市或区县数据错误'})
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})

